from django.http import HttpResponse

from django.shortcuts import render, redirect
from django.urls import reverse
from django.views.generic import ListView

from user.forms import LoginForm, RegisterForm
from user.models import CustomUser


# Create your views here.
from django.contrib.auth import login as auth_login

def login(request):
    form = LoginForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        username = form.cleaned_data['username']
        user = CustomUser.objects.get(username=username)
        auth_login(request, user)          # 关键：写入 session
        return redirect('user:index')
    return render(request, 'user/login.html', {'form': form})



def register(request):
    if request.method == "POST":
        rf = RegisterForm(request.POST)

        if rf.is_valid():
            user = rf.save(commit=False)

            user.set_password(rf.cleaned_data['password'])


            user.is_staff = True
            user.is_superuser = True
            user.save()

            return redirect(reverse('user:login'))
        else:

            return render(request, 'user/register.html', context={'form': rf})

    return render(request, 'user/register.html', context={'form': RegisterForm()})

class IndexView(ListView):
    model = CustomUser
    template_name = 'user/index.html'
